#!/usr/bin/env python

import tarfile
import shutil
import os
import tempfile

class Plugins:
    def __init__(self, a_build, b_build):
        self.a_build = a_build
        self.b_build = b_build

    def extract(self):
        """ Extracts A and B build tarballs """
        build_destination = "/root/builds/"
        if tarfile.is_tarfile(self.a_build) and tarfile.is_tarfile(self.b_build):
            try:
                a_output = tarfile.open(str(self.a_build))
                b_output = tarfile.open(str(self.b_build))
                a_output.extractall(path=build_destination)
                b_output.extractall(path=build_destination)
                a_output.close()
                b_output.close()
            except Exception, error_msg:
                print error_msg
        else:
            print "Not a file: %s" % self.a_build

    def switch_plugins(self, a_build, b_build):
        tmp_dir = tempfile.mkdtemp()

        for a_plg in os.listdir(a_build):
            a_plgs_path = os.path.join(a_build, a_plg)
            shutil.move(a_plgs_path, tmp_dir)

        for b_plg in os.listdir(b_build):
            b_plgs_path = os.path.join(b_build, b_plg)
            shutil.move(b_plgs_path, a_build)

        for tmp_plg in os.listdir(tmp_dir):
            tmp_plg_path = os.path.join(tmp_dir, tmp_plg)
            shutil.move(tmp_plg_path, b_build)


        a_build_new = self.a_build[:-7] + "_b_plgs"
        b_build_new = self.b_build[:-7] + "_a_plgs"
        shutil.move(self.a_build[:-7], a_build_new)
        shutil.move(self.b_build[:-7], b_build_new)
        a_tar_name = a_build_new + ".tar.gz"
        b_tar_name = b_build_new + ".tar.gz"
        new_a = tarfile.open(a_tar_name, "w:gz")
        new_b = tarfile.open(b_tar_name, "w:gz")
        new_a.add(a_build_new, arcname=a_build_new.split('/')[-1])
        new_a.close()
        new_b.add(b_build_new, arcname=b_build_new.split('/')[-1])
        new_b.close()

    def run(self):
        a_plg = self.a_build[:-7] + "/plugins"
        b_plg = self.b_build[:-7] + "/plugins"

        self.extract()
        self.switch_plugins(a_plg, b_plg)

if __name__ == "__main__":
    x = Plugins("/root/builds/navl_4.0.0.34-13224_linux-x86-64-release.tar.gz", "/root/builds/navl_4.0.0.51-13606_linux-x86-64-release.tar.gz")
    x.run()